package com.github.houkunlin.ui;

import com.github.houkunlin.model.DataTableModel;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.project.DumbAware;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.Key;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.ui.EditorNotificationProvider;
import com.weinisuo.plugin.generate.template.TplType;
import lombok.Getter;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import javax.swing.*;
import java.util.Map;
import java.util.function.Function;

public class TemplateEditorNotificationProvider implements DumbAware, EditorNotificationProvider {

    public static final Key<TemplateNotificationPanel> KEY = Key.create("template.notificationPanel");

    private static final Logger LOG = Logger.getInstance(TemplateEditorNotificationProvider.class);

    @Getter
    private static volatile Map<String, DataTableModel> projectDataTableModelMap = new java.util.concurrent.ConcurrentHashMap<>();

    public @NotNull Key<TemplateNotificationPanel> getKey(){
        return KEY;
    }

    public @Nullable TemplateNotificationPanel createNotificationPanel(
        @NotNull VirtualFile file, @NotNull FileEditor fileEditor, @NotNull Project project){
        TplType tplType = TplType.create(file.getName());
        if(tplType == TplType.NONE){
            return null;
        }
        DataTableModel dataTableModel = projectDataTableModelMap
            .computeIfAbsent(project.getLocationHash(), (k) -> new DataTableModel(project));
        return new TemplateNotificationPanel(dataTableModel, project);
    }

    @Override
    public @NotNull Function<? super @NotNull FileEditor, ? extends @Nullable JComponent> collectNotificationData(
        @NotNull Project project, @NotNull VirtualFile file){
        return fileEditor -> createNotificationPanel(file, fileEditor, project);
    }
}
